<template>
  <div class="yingShouHeXiaoPage">
    <el-card class="card-box" shadow="never">
      <div class="head">
        <h1>{{detailsInfo.projectName}}</h1>
      </div>
      <div class="info-box">
        <el-form>
          <el-row>
            <el-col  :span="6">
              <el-form-item class="form-item-margin_bottom" label="合同名称:">
                <span>{{detailsInfo.contractName}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="合同编号:">
                <span>{{detailsInfo.contractId}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="合同类型:">
                <span>{{['','新签','续签','退租'][detailsInfo.contractType]}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="资产名称:">
                <span>{{detailsInfo.assetsName}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="位置:">
                <span>{{detailsInfo.street}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="承租方:">
                <span>{{detailsInfo.customerNames}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="4.5">
              <el-form-item class="form-item-margin_bottom" label="面积:">
                <span>{{detailsInfo.leaseTotalArea}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="已缴/合同金额:">
                <span>{{(detailsInfo.paidContractTotalPrice || 0)+'/'+detailsInfo.contractTotalPrice}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="已履期数/合同期数:">
                <span>{{detailsInfo.contractPaidPeriodsNum+'/'+detailsInfo.contractPeriodsNum}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="服务期限:">
                <span>{{detailsInfo.signStartTime+'/'+detailsInfo.signEndTime}}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-divider/>
    <CommonTitle :titleName="`保证金:${detailsInfo.deposit} ${['','待缴','已缴','待退','已退','待补'][detailsInfo.depositStatus] || ''}`" class="m-t20"></CommonTitle>
    <public-table
        ref="publicTableRef"
        :index="false"
        :isPaging="false"
        :page="page"
        :selection="true"
        :disabledSelectAll="true"
         border
        :tableData="tableData"
        :tableOption.sync="tableOption"
        :rowStyles="rowStyles"
        @selectClick="selectClick"
    >
    </public-table>
    <el-divider/>
    <el-card class="card-box m-t30" shadow="never">
      <div class="info-box">
        <el-form>
          <el-row>
            <el-col  :span="6">
              <el-form-item class="form-item-margin_bottom" label="本次缴费:">
                <span >{{numberOfPeriods}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="本次缴费时长:">
                <span>{{paymentDuration}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="缴费方式:">
                <span>按{{['','月','季','半年','年'][detailsInfo.payType]}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="账户余额:">
                <span>{{detailsInfo.accountBalance}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="核销后余额:">
                <!-- 核销后余额 =  已收 - 应收 + 账户余额         -->
                <span>{{yuE}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="流水号:">
                <el-tooltip
                    :disabled="serialNumber.num<3"
                    effect="dark"
                    :content="serialNumber.title"
                    placement="top-start"
                >
                  <span>{{serialNumber.serialNumberTitle}}</span>
                </el-tooltip>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item class="form-item-margin_bottom" label="备注:">
                <el-input v-model="param.remarks" placeholder="非必填"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6">

            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="6"></el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-divider/>
    <el-descriptions
        class="margin-top"
        title="当前开票信息："
        :column="3"
        border
    >
      <template #extra>
        <el-button type="primary" @click="updateInvoicing">修改</el-button>
      </template>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            名称：
          </div>
        </template>
        {{InvoicingInfo.invoiceHeader || "暂无"}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            地址：
          </div>
        </template>
        {{InvoicingInfo.invoiceAddress || "暂无"}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            税号：
          </div>
        </template>
        {{InvoicingInfo.dutyParagraph || "暂无"}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            电话：
          </div>
        </template>
        {{InvoicingInfo.invoicePhone || "暂无"}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            开户银行：
          </div>
        </template>
        {{InvoicingInfo.openingBank || "暂无"}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            银行账户：
          </div>
        </template>
        {{InvoicingInfo.bankAccount || "暂无"}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            选择开票类型：
          </div>
        </template>
        <el-select v-model="param.type" placeholder="请选择(必填)">
          <el-option v-for="(item,index) in invoiceType" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            选择财务人员：
          </div>
        </template>
        <el-select v-model="param.financialUserId" placeholder="请选择(必填)">
          <el-option v-for="(item,index) in userList" :key="index" :label="item.userName" :value="item.userId"></el-option>
        </el-select>
      </el-descriptions-item>
    </el-descriptions>
    <div class="button-wrap d-flex a-center j-center m-t30">
      <el-button @click="onCancel" color="#ff8350" style="color: #FFFFFF;padding: 0 20px">取消</el-button>
      <el-button @click="onSubmit" color="#93d6ff" style="color: #FFFFFF;padding: 0 20px">确认核销</el-button>
    </div>
  </div>

  <!-- 修改开票信息 -->
  <add-invoicing-dialog
      v-model:visible="visible"
      :form="InvoicingInfo"
      @onConfirm="onConfirm"
  />
</template>

<script setup>
import {leaseApi} from "@/api/lease";
import { ref,onMounted,reactive,computed } from "vue";
import {useRouter} from "vue-router";
import CommonTitle from "@/components/CommonTitle.vue";
import PublicTable from "@/components/PublicTable";
import {ElCard,ElForm,ElFormItem,ElRow,ElCol,ElMessage,ElInput,ElDivider,ElDescriptions,ElDescriptionsItem,ElSelect,ElOption} from "element-plus";
import {invoiceType} from "@/common/dict/dictCollect";
import AddInvoicingDialog from "@/views/assetManagement/collaborativeManagement/InvoicingManagement/components/addInvoicingDialog";

const router = useRouter();
const contractId = router.currentRoute.value.params.contractId;
const detailsInfo = ref({});

const page = reactive({
  total: 0,
  current: 1,
  size: 10
});
const tableData = ref([]);
const tableOption = ref([
  { label: '期数', prop: 'numberOfPeriods',align:'center' },
  { label: '期间 ', prop: '',overHidden:false,align:'center',formatter:(val,row)=>{
      return row.payStartTime+'-'+row.payEndTime;
    } },
  { label: '租赁面积  ', prop: 'leaseTotalArea',overHidden:false,align:'center' },
  { label: '递增 ', prop: 'increaseRatio',overHidden:false,align:'center' },
  { label: '租金单价 ', prop: 'rentUnitPrice',overHidden:false,align:'center' },
  { label: '', prop: 'receivableRent',overHidden:false,align:'center' }
]);
let currentArr = ref([]);

const rowStyles = ({row,rowIndex}) => {
  if(row.type===1){
    return 'background:#ccc';
  }
  if(row.type===2){
    return 'background:rgb(219, 93, 70)';
  }
}


// 应收核销详情
const getReceivableCollectionInfo = () => {
  leaseApi.getReceivableCollectionInfo({
    contractId:contractId
  }).then(res=>{
      res.data.list.forEach((item,index)=>{
       if(item.type===1 || item.type=== 3){
         item.disabled = true;
       }
      });
      detailsInfo.value = res.data;
      tableData.value = res.data.list;
      tableOption.value[tableOption.value.length-1].label = ['','月','季','年'][detailsInfo.value.payType]+'租金';
  });
}

const param = reactive({
  remarks:'',
  type:'',// 发票类型
  financialUserId:'',// 财务人员
  businessId:'', // 业务id
});

const InvoicingInfo = ref({});
// 查询开票信息
const getInvoicingInfo = () => {
  leaseApi.getInvoicingInfo({
    contractId:contractId
  }).then(res=>{
    InvoicingInfo.value = res.data;
  });
}

// 确认核销
const onSubmit  = () => {
  if(currentArr.value.length===0){
    ElMessage.warning('请选择需要应收的数据!');
    return;
  }
  if(param.type===''){
    ElMessage.warning('请选择开票类型!');
    return;
  }
  if(param.financialUserId===''){
    ElMessage.warning('请选择财务人员!');
    return;
  }
  let obj = {
    list:[],
    addDto:{
      ...param,
      ...InvoicingInfo.value,
        amount:0,
    }
  };
  currentArr.value.forEach(item=>{
    obj.list.push({
      contractId:contractId,
      payPlanId:item.payPlanId,
      numberOfPeriods:item.numberOfPeriods,
      receivableRent:item.receivableRent,
      receivedRent:item.receivableRent,
      remarks:param.remarks
    });
    obj.addDto.amount = obj.addDto.amount + item.receivedRent;
  });
  if(currentArr.value.length > 0){
      obj.addDto.startTime = currentArr.value[0].payStartTime;
      obj.addDto.endTime = currentArr.value[currentArr.value.length-1].payStartTime;
  }
  leaseApi.contractCollectionAdd(obj).then(res=>{
    if(res.code == 200){
      ElMessage.success('核销成功!');
      router.push({ path: "/asset/management/managementIndex", query: {} });
    }
  });
}

const onCancel = () => {
  router.push({ path: "/asset/management/managementIndex", query: {} });
}

const publicTableRef = ref(null);
const selectClick = (row) => {
  let i = currentArr.value.findIndex(x=>x.numberOfPeriods===row.numberOfPeriods);

  if(i!==-1){ // 存在
    currentArr.value.splice(i,1);
  }

  if(i===-1 && currentArr.value.length === 0){
    currentArr.value.push(row);
    return;
  }

  if(i===-1 && currentArr.value.length > 0){ // 不存在
    let bool = false;
    for (let j = 0;j < currentArr.value.length;j++){
      if(currentArr.value[j].numberOfPeriods === (row.numberOfPeriods -1)){
        bool = true;
        break;
      }
    }
    if(!bool){
      publicTableRef.value.toggleRowSelection(row,false);
      ElMessage.warning('请按照期数顺序选择!');
      return;
    }
    currentArr.value.push(row);
  }
}

// 缴费期数
const numberOfPeriods = computed(()=>{
 return  currentArr.value.map((item)=>{
    return  '第'+item.numberOfPeriods+'期';
  }).join(',') || '暂无';
});

// 本次缴费时长
const paymentDuration = computed(()=>{
  if(currentArr.value.length!==0){
    return  currentArr.value[0].payStartTime + '-' + currentArr.value[currentArr.value.length-1].payEndTime
  }
  return '暂无';
});

// 本次到账金额
const receivedAmount = computed(()=>{
  let count = 0;
  currentArr.value.forEach(item=>{
    count = count + item.receivedRent;
  });
  return count;
});

// 流水号
const serialNumber = computed(()=>{
  let arr = [];
  currentArr.value.forEach(item=>{
    arr.push(item.payPlanId);
  });
 // return  arr.join(',') || '暂无';
  return {
    title:arr.join(',') || '暂无',
    serialNumberTitle:arr.length>2?arr.slice(0,2).join(',')+'...':arr.join(',') || '暂无',
    num:arr.length
  }
});

// 核销后余额
const yuE = computed(()=>{
  let receivableRent = 0;
  currentArr.value.forEach(item=>{
    receivableRent = receivableRent + item.receivableRent;
  });
  return detailsInfo.value.accountBalance - receivableRent;
});

const userList = ref([]);
const getUserList = () => {
  leaseApi.getUserList().then(res=>{
    userList.value = res.data;
  });
}

const visible = ref(false);
// 修改开票信息
const updateInvoicing = () => {
  visible.value = true;
}

const onConfirm = () => {
  getInvoicingInfo();
}

onMounted(()=>{
  getReceivableCollectionInfo();
  getInvoicingInfo();
  getUserList();
});
</script>

<style lang="scss" scoped>
.yingShouHeXiaoPage{
  .form-item-margin_bottom{
    margin-bottom: 0!important;
  }
  .card-box{
    width: 90%;
  }
  .button-wrap{}
}
</style>
